import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
import NotFound from '@/views/404/index.vue'
import subRoutes from './modules'

let routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home,
        meta: { title: '首页' }
      },
      ...subRoutes
    ]
  }, {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
  }, {
    path: '/register',
    component: () => import('@/views/login/reg.vue'),
  }, {
    path: '/404',
    component: NotFound,
    meta: { title: '404' }
  }, {
    path: '/:catchAll(.*)',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior: () => ({ top: 0, left: 0, behavior: 'smooth' }),
})

import { siteTitle } from '@/config'

router.beforeEach(async (to) => {
  if (to.meta.title) document.title = to.meta.title + ' | ' + siteTitle
  if (to.meta.guard) return to.meta.guard()
})

import { asyncRoutes } from './asyncRoutes'
import moderatorRoutes from './moderatorRoutes'

const resetRouterFns = []

const resetRouter = () => resetRouterFns.forEach(fn => fn())


function addRouteByRoles(roles) {
  resetRouter()

  const roleRoutes = {
    admin: [...asyncRoutes, ...moderatorRoutes],
    staff: [...moderatorRoutes],
  }

  roles.forEach(role => {
    (roleRoutes[role] || []).forEach(
      route => resetRouterFns.push(router.addRoute(route))
    )
  })
}


export default router

export {
  resetRouter,
  addRouteByRoles
}